import { useState, useEffect } from 'react';
import { Button, Checkbox, Form, Input, message } from 'antd';
import { usernameRule, passwordRule } from '@/validator/loginValidate';
import userModel from '@/models/userModel';
import { useHistory } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'

const LoginForm = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const uid = useSelector(state => state.user.uid)

  let [loading, setLoading] = useState(() => false)

  const [form] = Form.useForm();


  useEffect(() => {
    if (uid > 0) {
      // uid大于0，表示登录成功
      if (loading) {
        message.success({
          content: '登录成功',
          duration: 1,
          onClose: () => {
            setLoading(false)
            history.push('/admin')
          }
        })
      } else {
        history.push('/admin')
      }
    }
  }, [uid])

  const onFinish = async values => {
    setLoading(true)
    dispatch({ type: 'fetchLogin', deta: values })




    // // console.log('Success:', values);
    // let ret = await userModel.login(values)
    // setLoading(false)
    // //跳转
    // history.push('/admin')
    // console.log(ret);
  };

  const onFinishFailed = (errorInfo) => {
    setLoading(true)

    message.error({
      content: '输入数据不完整，请重新输入',
      duration: 2,
      onClose: () => setLoading(false)
    })
  };

  return (
    <Form
      form={form}
      initialValues={{ remember: true }}
      labelCol={{
        span: 6,
      }}
      wrapperCol={{
        span: 14,
      }}
      autoComplete="off"
      //验证成功触发
      onFinish={onFinish}
      // 验证失败触发
      onFinishFailed={onFinishFailed}
    >
      <Form.Item
        label="用户名："
        name="username"
        rules={usernameRule()}
      >
        <Input placeholder='请输入您的用户名' />
      </Form.Item>

      <Form.Item
        label="密&emsp;码："
        name="password"
        rules={passwordRule()}
      >
        {/* <Input.Password /> */}
        <Input placeholder='请输入您的密码' />
      </Form.Item>

      <Form.Item
        name="remember"
        valuePropName="checked"
        wrapperCol={{
          offset: 6,
          span: 14,
        }}
      >
        <Checkbox>记住密码</Checkbox>
      </Form.Item>

      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit" loading={loading}>
          登录
        </Button>
        &emsp;
        <Button type="default" onClick={() => {
          form.resetFields()
        }}>
          重置
        </Button>
      </Form.Item>
    </Form >
  );
}

export default LoginForm;
